﻿//-----------------------------------------------------------------------------
//<filedescription file="IntegrationKit.Console.cs" company="Microsoft">
//  <copyright>
//     Copyright © Microsoft Corporation.  All rights reserved.
//     ***  DESIGNATED SAMPLE CODE (per the included software license terms) ***
//      THIS CODE SAMPLE IS MADE AVAILABLE TO YOU WITHOUT WARRANTY OF ANY KIND
//      AND CONFERS NO RIGHTS ON YOU WHATSOEVER EXCEPT THE RIGHT TO REVIEW IT
//      SOLELY AS A REFERENCE.  THE ENTIRE RISK OF USE OR RESULTS FROM USE OF
//      THIS CODE SAMPLE REMAINS WITH YOU.
//  </copyright>
//  <purpose>
//     Provides utility methods specific to the Configuration Manager
//     admin console.
//  </purpose>
//  <notes>
//  </notes>
//</filedescription>
//-----------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using Microsoft.ConfigurationManagement.AdminConsole;
using Microsoft.ConfigurationManagement.AdminConsole.Common;
using Microsoft.ConfigurationManagement.AdminConsole.OsdCommon;
using Microsoft.ConfigurationManagement.AdminConsole.TaskSequenceEditor;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
using Microsoft.Win32;


namespace Microsoft.ConfigurationManagement.IntegrationDevelopmentKit
{
    /// <summary>
    /// 
    /// </summary>
    public partial class IntegrationKitUtilities
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="folderName"></param>
        /// <param name="objectType"></param>
        /// <param name="parentFolderID"></param>
        /// <param name="searchXML"></param>
        /// <returns></returns>
        public static IResultObject CreateConsoleFolder(WqlConnectionManager connection, string folderName, ContainerItemType objectType, int parentFolderID, string searchXML)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (string.IsNullOrEmpty(folderName))
            {
                throw new System.ArgumentException("folderName", Properties.Resources.Error_InvalidParameter);
            }
            if (objectType < 0)
            {
                throw new System.ArgumentException("objectType", Properties.Resources.Error_InvalidParameter);
            }

            try
            {
                string parentFolderName = string.Empty;
                if (parentFolderID > 0)
                {
                    parentFolderName = GetConsoleFolderName(connection, parentFolderID);
                }
                //Console.WriteLine("\nCreateConsoleFolder() passed initial checks\n");
                IResultObject folder = null;

                LogLine(LogFile, "CreateConsoleFolder: Getting folder by name: '" + folderName  + "'", DebugEnabled);
                    
                folder = GetFolderByName(connection, folderName, objectType, parentFolderName);
                if (folder != null)
                {
                    LogLine(LogFile, "CreateConsoleFolder: Folder already exists. Returning existing object.", DebugEnabled);
                    return folder;
                }

                LogLine(LogFile, "CreateConsoleFolder: GetFolderByName() returned null. Creating a new instance.", DebugEnabled);

                IResultObject newFolder = connection.CreateInstance("SMS_ObjectContainerNode");
                if (newFolder == null)
                {
                    LogLine(LogFile, "CreateConsoleFolder: CreateInstance(\"SMS_ObjectContainerNode\") failed to create an object.", DebugEnabled);
                    return null;
                }
                //Console.WriteLine("Created a new instance of a folder object. \n");
                //Console.WriteLine("Name                  :" + folderName + " \n");
                //Console.WriteLine("ObjectType            :" + (int)objectType + " \n");
                //Console.WriteLine("SearchFolder          :" + "false" + " \n");
                //Console.WriteLine("FolderFlags           :" + "0" + " \n");


                newFolder["Name"].StringValue = folderName;
                newFolder["ObjectType"].IntegerValue = (int)objectType;
                if (parentFolderID > 0)
                {
                    newFolder["ParentContainerNodeID"].IntegerValue = parentFolderID;
                    LogLine(LogFile, "CreateConsoleFolder: ParentContainerNodeID :" + parentFolderID, DebugEnabled);
                }
                else
                {
                    newFolder["ParentContainerNodeID"].IntegerValue = 0;
                    LogLine(LogFile, "CreateConsoleFolder: ParentContainerNodeID : 0", DebugEnabled);
                }

                if (string.IsNullOrEmpty(searchXML) == false)
                {
                    newFolder["SearchFolder"].BooleanValue = true;
                    newFolder["SearchString"].StringValue = searchXML;
                    newFolder["FolderFlags"].IntegerValue = 0;
                }
                else
                {
                    newFolder["SearchFolder"].BooleanValue = false;
                    newFolder["SearchString"].StringValue = "";
                    newFolder["FolderFlags"].IntegerValue = 0;
                }

                LogLine(LogFile, "CreateConsoleFolder: Set the folder object properties. Now calling Put()", DebugEnabled);
                //newFolder.AutoCommit = true;
                newFolder.Put();
                newFolder.Get();

                return newFolder;

            }
            catch (SmsQueryException qex)
            {
                LogLine(LogFile, "WMI Exception occurred in GetFolderByName() : " + qex.ExtendStatusErrorCode + "\n" + qex.Details + "\n" + qex.Data + "\n" + qex.TargetSite + "\n" + qex.InnerException + "\n" + qex.Message + "\n" + qex.StackTrace, DebugEnabled);
                IntegrationKitUtilities.LogException(LogFile, qex);
                return null;
            }
            catch (Exception ex)
            {
                LogLine(LogFile, "WMI Exception occured in GetFolderByName().\n" + ex.Message, DebugEnabled);
                IntegrationKitUtilities.LogException(LogFile, ex);
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="nodeID"></param>
        /// <returns></returns>
        public static string GetConsoleFolderName(WqlConnectionManager connection, Int32 nodeID)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (nodeID < 0)
            {
                throw new System.ArgumentException("nodeID", Properties.Resources.Error_InvalidParameter);
            }
            try
            {
                IResultObject folder = connection.GetInstance(@"SMS_ObjectContainerNode.ContainerNodeID=" + nodeID + "");
                if (folder == null)
                {
                    return null;
                }
                string folderName = IntegrationKitUtilities.GetROStringProperty(folder, "Name");
                if (string.IsNullOrEmpty(folderName))
                {
                    return null;
                }
                return folderName;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="folderName"></param>
        /// <param name="objectType"></param>
        /// <param name="parentFolderName"></param>
        /// <returns></returns>
        public static IResultObject GetFolderByName(WqlConnectionManager connection, string folderName, ContainerItemType objectType, string parentFolderName)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (string.IsNullOrEmpty(folderName))
            {
                throw new System.ArgumentException("folderName", Properties.Resources.Error_InvalidParameter);
            }
            if (objectType < 0)
            {
                throw new System.ArgumentException("objectType", Properties.Resources.Error_InvalidParameter);
            }

            try
            {
                ////Console.WriteLine("GetFolderByName() passed initial checks\n");

                ////Console.WriteLine("Running query\n");

                string query = "SELECT * FROM SMS_ObjectContainerNode WHERE Name LIKE '" + FixWmiQueryString(folderName) + "' AND ObjectType=" + (int)objectType;
                if (connection.IsQueryValid(query) == false)
                {
                    //Console.WriteLine("Query INVALID: " + query + "\n");
                    throw new System.ArgumentException();
                }
                //Console.WriteLine("Query is valid: " + query + "\n");

                IResultObject folderObject = ExecuteNullableQuery(connection, query);
                if (folderObject == null)
                {
                    Console.WriteLine("Could not get folder by using name query. Name LIKE '" + FixWmiQueryString(folderName) + "'\n");
                    return null;
                }
                //Console.WriteLine("Query returned a value\n");
                ////Console.WriteLine("TOP Folder identifier: " + folderObject.UniqueIdentifier.ToString() + "\n");

                foreach (IResultObject fo in folderObject)
                {
                    ////Console.WriteLine("Folder identifier: " + fo.UniqueIdentifier.ToString() + "\n");

                    if (FoldersAreEqual(connection, folderName, objectType, parentFolderName, fo) == true)
                    {
                        return fo;
                    }
                }

                //Console.WriteLine("No matching folder found.\n");
                return null;
            }
            catch (SmsQueryException qex)
            {
                //Console.WriteLine("Exception occurred in GetFolderByName() : " + qex.ExtendStatusErrorCode + "\n" + qex.Details + "\n" + qex.Data + "\n" + qex.TargetSite + "\n" + qex.InnerException + "\n" + qex.Message + "\n" + qex.StackTrace);
                IntegrationKitUtilities.LogException(LogFile, qex);
                return null;
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Exception occured in GetFolderByName().\n" + ex.Message);
                IntegrationKitUtilities.LogException(LogFile, ex);
                return null;
            }
        }

        /// <summary>
        ///     
        /// </summary>
        /// <param name="connection" type="Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlConnectionManager">
        ///     <para>
        ///         
        ///     </para>
        /// </param>
        /// <param name="folderId" type="int">
        ///     <para>
        ///         
        ///     </para>
        /// </param>
        /// <returns>
        ///     A Microsoft.ConfigurationManagement.ManagementProvider.IResultObject value...
        /// </returns>
        public static IResultObject GetFolderById(WqlConnectionManager connection, Int32 folderId)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (folderId < 0)
            {
                throw new System.ArgumentException("folderId", Properties.Resources.Error_InvalidParameter);
            }
            

            try
            {
                IResultObject folder = connection.GetInstance(@"SMS_ObjectContainerNode.ContainerNodeID=" + folderId + "");
                if (folder == null)
                {
                    return null;
                }
                return folder;
            }
            catch (Exception qex)
            {
                //Console.WriteLine("Exception occurred in GetFolderByName() : " + qex.ExtendStatusErrorCode + "\n" + qex.Details + "\n" + qex.Data + "\n" + qex.TargetSite + "\n" + qex.InnerException + "\n" + qex.Message + "\n" + qex.StackTrace);
                IntegrationKitUtilities.LogException(LogFile, qex);
                return null;
            }
        }

        /// <summary>
        ///     
        /// </summary>
        /// <param name="connection" type="Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlConnectionManager">
        ///     <para>
        ///         
        ///     </para>
        /// </param>
        /// <param name="packageId" type="string">
        ///     <para>
        ///         
        ///     </para>
        /// </param>
        /// <returns>
        ///     A Microsoft.ConfigurationManagement.ManagementProvider.IResultObject value...
        /// </returns>
        public static Nullable<int> GetFolderIdForPackage(WqlConnectionManager connection, string packageId)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (string.IsNullOrEmpty(packageId))
            {
                throw new System.ArgumentException("packageId", Properties.Resources.Error_InvalidParameter);
            }
            

            try
            {
                string query = "SELECT * FROM SMS_ObjectContainerItem WHERE InstanceKey = '" + packageId + "'";
                if (connection.IsQueryValid(query) == false)
                {
                    //Console.WriteLine("Query INVALID: " + query + "\n");
                    throw new System.ArgumentException();
                }
                //Console.WriteLine("Query is valid: " + query + "\n");

                IResultObject folderObject = ExecuteNullableQuery(connection, query);
                if (folderObject == null)
                {
                    Console.WriteLine("Could not get the package's containing folder by using the package ID.");
                    Console.WriteLine("Query was:  \"SELECT * FROM SMS_ObjectContainerNode WHERE InstanceKey = '" + packageId + "'\"");
                    return null;
                }
                //Console.WriteLine("Query returned a value\n");
                ////Console.WriteLine("TOP Folder identifier: " + folderObject.UniqueIdentifier.ToString() + "\n");

                foreach (IResultObject fo in folderObject)
                {
                    ////Console.WriteLine("Folder identifier: " + fo.UniqueIdentifier.ToString() + "\n");
                    Nullable<int> folderId = GetROIntegerProperty(fo, "ContainerNodeID");
                    if (folderId.HasValue)
                    {
                        return folderId.Value;
                    }
                }

                Console.WriteLine("No matching folder found.\n");
                return null;
            }
            catch (SmsQueryException qex)
            {
                //Console.WriteLine("Exception occurred in GetFolderByName() : " + qex.ExtendStatusErrorCode + "\n" + qex.Details + "\n" + qex.Data + "\n" + qex.TargetSite + "\n" + qex.InnerException + "\n" + qex.Message + "\n" + qex.StackTrace);
                IntegrationKitUtilities.LogException(LogFile, qex);
                return null;
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Exception occured in GetFolderByName().\n" + ex.Message);
                IntegrationKitUtilities.LogException(LogFile, ex);
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="folderName"></param>
        /// <param name="objectType"></param>
        /// <param name="parentFolderName"></param>
        /// <param name="compareFolder"></param>
        /// <returns></returns>
        public static bool FoldersAreEqual(WqlConnectionManager connection, string folderName, ContainerItemType objectType, string parentFolderName, IResultObject compareFolder)
        {
            //Console.WriteLine("In FoldersAreEqual() \n");


            Nullable<int> parentFolderID = null;
            if (string.IsNullOrEmpty(parentFolderName))
            {
                //Console.WriteLine("Parent folder not specified \n");
                parentFolderID = 0;
            }
            else
            {
                //Console.WriteLine("Folder has a named parent - checking for that folder ID\n");
                IResultObject parentFolder = GetFolderByName(connection, parentFolderName, objectType, null);
                if (parentFolder == null)
                {
                    //Console.WriteLine("Couldn't locate parent folder.\n");
                    return false;
                }
                parentFolderID = IntegrationKitUtilities.GetROIntegerProperty(parentFolder, "ContainerNodeID");
                //Console.WriteLine("Parent folder ID = " + parentFolderID + "\n");

            }

            //Console.WriteLine("Getting properties 'name' and 'objectType'\n");

            string folderNodeName = IntegrationKitUtilities.GetROStringProperty(compareFolder, "Name");
            Nullable<int> folderObjectType = IntegrationKitUtilities.GetROIntegerProperty(compareFolder, "ObjectType");

            //Console.WriteLine("Existing Folder name: " + folderNodeName);
            //Console.WriteLine("     New Folder name: " + folderName + "\n");

            //Console.WriteLine("Existing Folder type: " + folderObjectType + "\n");
            //Console.WriteLine("     New Folder type: " + (int)objectType + "\n");

            if ((string.Compare(folderNodeName, folderName, StringComparison.CurrentCultureIgnoreCase) != 0) ||
                (folderObjectType.HasValue == false) ||
                (folderObjectType.Value != (int)objectType))
            {
                //Console.WriteLine("Folders don't match.\n");
                return false;
            }

            //Console.WriteLine("Found a matching folder name. Checking parent info. \n");

            if (parentFolderID.HasValue)
            {
                //Console.WriteLine("Parent specified: " + parentFolderID + " \n");

                if (parentFolderID.Value == IntegrationKitUtilities.GetROIntegerProperty(compareFolder, "ParentContainerNodeID"))
                {
                    //Console.WriteLine("Folders match.\n");
                    return true;
                }
                else
                {
                    //Console.WriteLine("Not a match. The folder found has a different parent.\n");
                    return false;
                }
            }
            else
            {
                Nullable<int> compareFolderID = IntegrationKitUtilities.GetROIntegerProperty(compareFolder, "ParentContainerNodeID");
                if ((compareFolderID.HasValue) && (compareFolderID.Value == 0))
                {
                    //Console.WriteLine("Folders match.\n");
                    return true;
                }
                else
                {
                    //Console.WriteLine("Not a match. The folder found has a parent.\n");
                    return false;
                }
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="objectID"></param>
        /// <param name="objectType"></param>
        /// <param name="folderID"></param>
        /// <returns></returns>
        public static IResultObject CreateConsoleFolderItem(WqlConnectionManager connection, string objectID, ContainerItemType objectType, Int32 folderID)
        {
            LogLine(LogFile, "Now in CreateConsoleFolderItem()", DebugEnabled);
            
            if (connection == null)
            {
                LogLine(LogFile, "connection parameter passed in to CreateConsoleFolderitem was null", DebugEnabled); 
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (string.IsNullOrEmpty(objectID))
            {
                LogLine(LogFile, "objectID parameter passed in to CreateConsoleFolderitem was null", DebugEnabled);
                throw new System.ArgumentException("objectID", Properties.Resources.Error_InvalidParameter);
            }
            if ((int)objectType < 0)
            {
                LogLine(LogFile, "objectType parameter passed in to CreateConsoleFolderitem was invalid: [" + objectType.ToString() + "]", DebugEnabled);
                throw new System.ArgumentException("objectType", Properties.Resources.Error_InvalidParameter);
            }
            if (folderID < 0)
            {
                folderID = 0;
            }
            LogLine(LogFile, "ObjectID: " + objectID, DebugEnabled);
            LogLine(LogFile, "ObjectType = " + objectType + "(enum) / " + (int)objectType + " (int)", DebugEnabled);

            try
            {
                // first look up any existing folder item referencing this package and use that if there is one
                IResultObject folderItem = null;
                string query = "Select * From SMS_ObjectContainerItem Where InstanceKey='" + objectID + "'";

                if (connection.IsQueryValid(query))
                {
                    query = connection.EscapeQueryString(query, ConnectionManagerBase.EscapeQuoteType.DoubleQuote);
                    LogLine(LogFile, "Query is valid - querying SMS_ObjectContainerNode for: \n" + query, DebugEnabled);
                    folderItem = ExecuteNullableQuery(connection, query);
                }
                else
                {
                    LogLine(LogFile, "Error: SMS_ObjectContainerNode query was not valid: \n" + query, DebugEnabled);
                    return null;
                }
                if (folderItem != null)
                {
                    Nullable<int> memberID = null;
                    foreach (IResultObject item in folderItem)
                    {
                        item.AutoRefresh = true;
                        memberID = IntegrationKitUtilities.GetROIntegerProperty(item, "MemberID");
                        break;
                    }

                    // open the instance for editing
                    if (memberID.HasValue == false)
                    {
                        LogLine(LogFile, "Unable to get memberID from folder item object. Resetting the object so a new one will be created.", DebugEnabled);
                        folderItem = null;
                    }
                    else
                    {
                        folderItem = connection.GetInstance("SMS_ObjectContainerItem.MemberID=" + memberID.Value);
                        if (folderItem == null)
                        {
                            LogLine(LogFile, "Folder item object was still null after GetInstance.", DebugEnabled);
                            return null;
                        }
                        LogLine(LogFile, "Existing folder item object instance opened for editing.", DebugEnabled);
                    }
                }
                if (folderItem == null)
                {
                    // Create new folder item object.
                    folderItem = connection.CreateInstance("SMS_ObjectContainerItem");
                    if (folderItem == null)
                    {
                        LogLine(LogFile, "Folder item object was still null after CreateInstance.", DebugEnabled);
                        return null;
                    }
                    LogLine(LogFile, "New folder item object instance created.", DebugEnabled);
                }


                LogLine(LogFile, "Updating properties.", DebugEnabled);

                LogLine(LogFile, "InstanceKey     : " + objectID, DebugEnabled);
                LogLine(LogFile, "ObjectType      : " + (int)objectType, DebugEnabled);
                LogLine(LogFile, "ContainerNodeID : " + folderID, DebugEnabled);

                folderItem["InstanceKey"].StringValue = objectID;
                folderItem["ObjectType"].IntegerValue = (int)objectType;
                folderItem["ContainerNodeID"].IntegerValue = folderID;
                //folderItem.AutoCommit = true;

                folderItem.Put();
                return folderItem;

            }
            catch (SmsQueryException qex)
            {
                LogLine(LogFile, "Exception occurred in CreateConsoleFolderItem() : " + qex.ExtendStatusErrorCode + "\n" + qex.Details + "\n" + qex.Data + "\n" + qex.TargetSite + "\n" + qex.InnerException + "\n" + qex.Message + "\n" + qex.StackTrace, DebugEnabled);
                IntegrationKitUtilities.LogException(LogFile, qex);
                return null; 
            }
            catch (Exception ex)
            {
                LogLine(LogFile, "Exception occured in CreateConsoleFolderItem().\n" + ex.Message, DebugEnabled);
                IntegrationKitUtilities.LogException(LogFile, ex);
                return null;
            }
        }

        /// <summary>
        /// Creates a link between an object and a driver that contains it (places the object in the driver). Uses the name of the object and the name of the driver instead of requiring actual IDs.
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="objectName"></param>
        /// <param name="objectType"></param>
        /// <param name="folderName"></param>
        /// <returns>An IResultObject containing the item object placed int he driver</returns>
        public static IResultObject CreateConsoleFolderItem(WqlConnectionManager connection, string objectName, ContainerItemType objectType, string folderName)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (string.IsNullOrEmpty(objectName))
            {
                throw new System.ArgumentException("objectName", Properties.Resources.Error_InvalidParameter);
            }
            if (objectType < 0)
            {
                throw new System.ArgumentException("objectType", Properties.Resources.Error_InvalidParameter);
            }

            try
            {
                IResultObject itemObject = GetContainerItemByName(connection, objectName, objectType);
                if (itemObject == null)
                {
                    return null;
                }
                string instanceID = GetObjectInstanceID(itemObject, objectType);
                if (string.IsNullOrEmpty(instanceID))
                {
                    return null;
                }

                IResultObject destinationFolderObject = GetFolderByName(connection, folderName, objectType, null);
                if (destinationFolderObject == null)
                {
                    return null;
                }
                Nullable<int> destinationContainerID = GetROIntegerProperty(destinationFolderObject, "ContainerNodeID");
                if (destinationContainerID.HasValue == false)
                {
                    return null;
                }


                IResultObject folderItem = connection.CreateInstance("SMS_ObjectContainerItem");
                if (folderItem == null)
                {
                    return null;
                }
                folderItem["InstanceKey"].StringValue = instanceID;
                folderItem["ObjectType"].IntegerValue = (int)objectType;
                folderItem["ContainerNodeID"].IntegerValue = destinationContainerID.Value;
                //folderItem.AutoCommit = true;
                folderItem.Put();
                return folderItem;

            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Deletes a driver specified by is ContainerNodeID
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="nodeID"></param>
        /// <returns>Boolean value indicating success or failure of the deletion.</returns>
        public static bool DeleteConsoleFolder(WqlConnectionManager connection, Int32 nodeID)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (nodeID < 0)
            {
                throw new System.ArgumentException("nodeID", Properties.Resources.Error_InvalidParameter);
            }
            try
            {
                IResultObject folder = connection.GetInstance(@"SMS_ObjectContainerNode.ContainerNodeID=" + nodeID + "");
                if (folder == null)
                {
                    LogLine(LogFile, "Folder not found.", DebugEnabled);
                    return false;
                }
                else
                //foreach (IResultObject f in folder)
                {
                    //modified 2/5/09 by rhearn to add checking to ensure folder is empty before deleting.

                    string query = "SELECT * From SMS_ObjectContainerItem  WHERE ContainerNodeID = '" + nodeID + "'";
                    LogLine(LogFile, "Checking for folder contents: (SELECT * From SMS_ObjectContainerItem  WHERE ContainerNodeID = '" + nodeID + "')", DebugEnabled);
                    
                    IResultObject results = ExecuteNullableQuery(connection, query);
                    if ((results == null) || (GetNumberOfChildObjects(results) == 0))
                    {
                        LogLine(LogFile, "Deleting folder.", DebugEnabled);
                        folder.Delete();
                        return true;
                    }
                    else
                    {
                        LogLine(LogFile, "Folder not empty. Not deleting.", DebugEnabled);
                        return false;
                    }
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Deletes a driver by specifying the driver name, a driver type, and an optional parent driver name
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="folderName"></param>
        /// <param name="objectType"></param>
        /// <param name="parentFolderName"></param>
        /// <returns>A boolean value indiciating success or failure of the deletion.</returns>
        public static bool DeleteConsoleFolder(WqlConnectionManager connection, string folderName, ContainerItemType objectType, string parentFolderName)
        {
            if (connection == null)
            {
                throw new System.ArgumentException("connection", Properties.Resources.Error_InvalidParameter);
            }
            if (string.IsNullOrEmpty(folderName))
            {
                throw new System.ArgumentException("folderName", Properties.Resources.Error_InvalidParameter);
            }
            if (objectType < 0)
            {
                throw new System.ArgumentException("objectType", Properties.Resources.Error_InvalidParameter);
            }

            try
            {
                IResultObject folder = GetFolderByName(connection, folderName, objectType, parentFolderName);
                if (folder == null)
                {
                    return false;
                }
                else
                {
                    int? containerID = IntegrationKitUtilities.GetROIntegerProperty(folder, "ContainerNodeID");
                    if (containerID.HasValue)
                    {
                        if (DeleteConsoleFolder(connection, containerID.Value) == false)
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                        //IResultObject folderContents = connection.QueryProcessor.ExecuteQuery("Select * From SMS_ObjectContainerItem Where ContainerNodeId=" + containerID.Value.ToString());
                        //if (folderContents != null)
                        //{
                        //    foreach (IResultObject folderContent in folderContents)
                        //    {
                        //        return false;
                        //    }
                        //}
                        //else
                        //{
                        //    folder.Delete();
                        //    return true;
                        //}
                        
                    }
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

       
    }
}